package org.flint92.springboot.mbean.simple;

import javax.management.*;
import java.util.concurrent.atomic.AtomicLong;

import static javax.management.AttributeChangeNotification.ATTRIBUTE_CHANGE;

/**
 * @author flint92
 */
public class SimpleData extends NotificationBroadcasterSupport
        implements SimpleDataMBean, NotificationListener, NotificationFilter {
    private static final long serialVersionUID = 7961024793079869268L;

    private String data;

    private static final AtomicLong sequence = new AtomicLong();

    public SimpleData() {
        this.addNotificationListener(this, this, null);
    }

    @Override
    public void setData(String data) {
        String oldData = this.data;
        this.data = data;

        Notification notification = new AttributeChangeNotification(
                this,
                sequence.incrementAndGet(),
                System.currentTimeMillis(),
                "Data has changed from " + oldData + " to " + data,
                "data",
                String.class.getName(),
                oldData,
                data);

        sendNotification(notification);
    }

    @Override
    public String getData() {
        return this.data;
    }

    @Override
    public void displayData() {
        System.out.println(this.data);
    }

    @Override
    public void handleNotification(Notification notification, Object handback) {
        AttributeChangeNotification attributeChangeNotification = (AttributeChangeNotification) notification;

        String oldVal = (String) attributeChangeNotification.getOldValue();
        String newVal = (String) attributeChangeNotification.getNewValue();

        System.out.println(oldVal + "==>" + newVal);
    }

    @Override
    public boolean isNotificationEnabled(Notification notification) {
        if (AttributeChangeNotification.class.isAssignableFrom(notification.getClass())) {
            AttributeChangeNotification attributeChangeNotification = (AttributeChangeNotification) notification;
            return "data".equals(attributeChangeNotification.getAttributeName());
        }
        return false;
    }

    public MBeanNotificationInfo[] getNotificationInfo() {
        return new MBeanNotificationInfo[]{
                new MBeanNotificationInfo(
                        new String[]{ATTRIBUTE_CHANGE},
                        "Data Change Notification",
                        "Data Change Notification")
        };
    }
}
